﻿using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RescueApp.Data;
using RescueApp.Models;
using EFCoreRepository.Extensions;
using Microsoft.EntityFrameworkCore;
using System.Data;


namespace RescueApp.UI.Common
{
    public static class DbHelper
    {
        public static bool IsExistsWithSql(RescueContext db, int Id)
        {
            string sql = @"select * from [dbo].[TodoItem] where Id=@Id";
            IDictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("@Id", Id);
            SqlParameter[] parameters = dict.ToSqlParameters();
            var todoitems = db.SqlQuery<RescueApply>(sql, parameters);
            if (todoitems.Any())
            {
                return true;
            }
            return false;
        }

        public static DataTable SqlDataTable(this RescueContext db, string sql, IDictionary<string, object> parameters = null)
        {
            using (var connection = new SqlConnection(db.Database.GetDbConnection().ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(sql, connection))
                {
                    if (parameters != null)
                    {
                        foreach (var param in parameters)
                        {
                            command.Parameters.AddWithValue(param.Key, param.Value);
                        }
                    }

                    var adapter = new SqlDataAdapter(command);
                    var ds = new DataSet();
                    adapter.Fill(ds);
                    return ds.Tables[0];
                }
            }
        }

    }
}
